package com.panfeng.xcloud.boss.provider.member.lock;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class DistributedRedisLock {

    private Config config = new Config();
    private static RedissonClient redissonClient;

    @Value("${redisson.single.url}")
    private String url;
    @Value("${redisson.single.password}")
    private String password;

    private static final String LOCK_PREFIX = "redisson:";

    @PostConstruct
    public void init(){
        try {
            //集群
//            config.useClusterServers() //redis集群server
//                    .setScanInterval(2000) //设置集群状态扫描时间
//                    .setMasterConnectionPoolSize(10000) //设置主节点连接数
//                    .setSlaveConnectionPoolSize(10000)  //设置从节点连接数
//                    .addNodeAddress("redis://192.168.3.99:7001","redis://192.168.3.99:7002","redis://192.168.3.99:7003","redis://192.168.3.99:7004","redis://192.168.3.99:7005","redis://192.168.3.99:7006");

            //单机
            if(StringUtils.isNotBlank(password)){
                config.useSingleServer().setAddress(this.url).setPassword(this.password);
            }else{
                config.useSingleServer().setAddress(this.url);
            }

            //创建redissonClient
            redissonClient=Redisson.create(config);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void lock(String lockName){
        String key = LOCK_PREFIX + lockName;
        RLock rLock = redissonClient.getLock(key);
        rLock.lock(20, TimeUnit.MINUTES);
        log.info("======lock======"+Thread.currentThread().getName());
    }

    public static void unlock(String lockName){
        String key = LOCK_PREFIX + lockName;
        RLock rLock = redissonClient.getLock(key);
        rLock.unlock();
        log.info("======unlock======"+Thread.currentThread().getName());
    }

}
